// 打字机效果指令
export const typewriter = {
    mounted(el, binding) {
        const text = binding.value
        const speed = binding.arg || 100 // 默认速度100ms
        const callback = binding.modifiers.callback

        if (!text) return

        let index = 0
        el.textContent = ''

        function type() {
            if (index < text.length) {
                el.textContent += text[index]
                index++
                setTimeout(type, speed)
            } else if (callback) {
                // 触发完成事件
                el.dispatchEvent(new CustomEvent('typewriter-complete'))
            }
        }

        // 开始打字效果
        setTimeout(type, speed)
    },

    updated(el, binding) {
        // 如果文本发生变化，重新开始打字效果
        if (binding.value !== binding.oldValue) {
            const text = binding.value
            const speed = binding.arg || 100
            const callback = binding.modifiers.callback

            if (!text) {
                el.textContent = ''
                return
            }

            let index = 0
            el.textContent = ''

            function type() {
                if (index < text.length) {
                    el.textContent += text[index]
                    index++
                    setTimeout(type, speed)
                } else if (callback) {
                    el.dispatchEvent(new CustomEvent('typewriter-complete'))
                }
            }

            setTimeout(type, speed)
        }
    }
} 